import { type App } from 'vue'
import { Modal } from 'ant-design-vue'
import { Dialog as CoreDialog, DialogProps, IDialog } from '@idmy/core'
import { omit } from 'lodash-es'

const defaultProps = { okText: '确认', cancelText: '取消' }
const dialog = (method: keyof IDialog) => {
	return (props: DialogProps): Promise<void> => {
		const cfg = Object.assign({ ...defaultProps }, props)
		return new Promise((resolve, reject): void => {
			Modal[method]({
				...omit(cfg, 'xClosable', 'onClose'),
				cancelButtonProps: {
					disabled: props.cancelable === false,
				},
				closable: cfg.xClosable,
				keyboard: false,
				onCancel: async () => {
					//@ts-ignore
					await cfg.close?.(false)
					reject('close')
				},
				onOk: async (): Promise<void> => {
					//@ts-ignore
					await cfg.close?.(true)
					resolve()
				},
			})
		})
	}
}

const install = (app: App): void => {
	CoreDialog.confirm = dialog('confirm')
	CoreDialog.success = dialog('success')
	CoreDialog.error = dialog('error')
	CoreDialog.warn = dialog('warn')
	CoreDialog.info = dialog('info')
}

export default {
	install,
}
